Paquetes usado en el manejo de mapas.

library(tidyverse)
## ── Attaching packages ─────────────────────────────────────── tidyverse 1.3.0 ──
## ✓ ggplot2 3.3.2     ✓ purrr   0.3.4
## ✓ tibble  3.0.4     ✓ dplyr   1.0.2
## ✓ tidyr   1.1.2     ✓ stringr 1.4.0
## ✓ readr   1.4.0     ✓ forcats 0.5.0
## ── Conflicts ────────────────────────────────────────── tidyverse_conflicts() ──
## x dplyr::filter() masks stats::filter()
## x dplyr::lag()    masks stats::lag()
library(sf)
## Linking to GEOS 3.8.1, GDAL 3.1.3, PROJ 7.1.1
library(OpenStreetMap)
library(osmdata)
## Data (c) OpenStreetMap contributors, ODbL 1.0. https://www.openstreetmap.org/copyright
library(ggmap)
## Google's Terms of Service: https://cloud.google.com/maps-platform/terms/.
## Please cite ggmap if you use it! See citation("ggmap") for details.

Lectura de un arhivo tipo “shp” (Shape o Shapefile).

El el siguiente luagar se puede descargar el mapa de los barrios de Envigado en formato Shape o Shapefile (.shp).

https://www.datos.gov.co/Ordenamiento-Territorial/Barrios-Municipio-de-Envigado/wduw-u5s7

barrios_env <- 
  read_sf("./Barrios Municipio de Envigado/geo_export_02c40250-3fb7-4273-bc5b-8c05066da85d.shp")

Despliegue del mapa importado del formato “.shp”.

plot(st_geometry(barrios_env))

barrios_env
## Simple feature collection with 39 features and 9 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -75.60517 ymin: 6.141683 xmax: -75.55978 ymax: 6.188921
## geographic CRS: WGS84(DD)
## # A tibble: 39 x 10
##    barrio   cod hectareas   km_2 nombarrio objectid shape_area shape_leng zona 
##    <chr>  <dbl>     <dbl>  <dbl> <chr>        <dbl>      <dbl>      <dbl> <chr>
##  1 039       39     16.6  0.166  BOSQUES …        1    166170.      1732. 02   
##  2 038       38     22.7  0.227  VILLAGRA…        2    226544.      2363. 02   
##  3 036       36     18.4  0.184  PONTEVED…        3    183766.      1975. 02   
##  4 037       37     13.2  0.132  JARDINES         4    131625.      1696. 02   
##  5 009        9    134.   1.34   LAS VEGAS        5   1339512.      8151. 01   
##  6 008        8      6.71 0.0671 LAS CASI…        6     67091.      1084. 08   
##  7 010       10     23.1  0.231  LA PRIMA…        7    230520.      1930. 08   
##  8 011       11     34.4  0.344  LA PAZ           8    343515.      2959. 07   
##  9 012       12     30.6  0.306  MILAN VA…        9    306314.      2479. 08   
## 10 013       13     49.9  0.499  EL DORADO       10    498922.      3698. 07   
## # … with 29 more rows, and 1 more variable: geometry <POLYGON [°]>

Desde este mismo lugar se puede descargar en forma de base de datos, la misma información pero con una columna adicional que tiene el formato “wkt” para objetos de tipo espacial.

bd_barrios <- read.csv("Barrios.csv", encoding = "UTF-8")
bd_barrios_sf <- st_as_sf(bd_barrios, wkt  = "the_geom")
plot(st_geometry(bd_barrios_sf))

bd_barrios_sf
## Simple feature collection with 39 features and 9 fields
## geometry type:  MULTIPOLYGON
## dimension:      XY
## bbox:           xmin: -75.60517 ymin: 6.141683 xmax: -75.55978 ymax: 6.188921
## CRS:            NA
## First 10 features:
##    BARRIO OBJECTID         NOMBARRIO ZONA Cod  Hectareas        Km2 Shape_Leng
## 1      39        1 BOSQUES DE ZUÑIGA    2  39  16.617621 0.16617621   1731.536
## 2      38        2       VILLAGRANDE    2  38  22.655200 0.22655200   2363.385
## 3      36        3        PONTEVEDRA    2  36  18.377276 0.18377276   1974.681
## 4      37        4          JARDINES    2  37  13.163009 0.13163009   1695.531
## 5       9        5         LAS VEGAS    1   9 133.956030 1.33956030   8151.463
## 6       8        6       LAS CASITAS    8   8   6.709297 0.06709297   1083.836
## 7      10        7      LA PRIMAVERA    8  10  23.052831 0.23052831   1930.369
## 8      11        8            LA PAZ    7  11  34.352783 0.34352783   2959.244
## 9      12        9 MILAN VALLEJUELOS    8  12  30.632476 0.30632476   2478.794
## 10     13       10         EL DORADO    7  13  49.894015 0.49894015   3698.017
##    Shape_Area                       the_geom
## 1   166170.24 MULTIPOLYGON (((-75.58107 6...
## 2   226543.82 MULTIPOLYGON (((-75.58155 6...
## 3   183766.11 MULTIPOLYGON (((-75.58155 6...
## 4   131625.35 MULTIPOLYGON (((-75.58694 6...
## 5  1339512.16 MULTIPOLYGON (((-75.58154 6...
## 6    67090.56 MULTIPOLYGON (((-75.60182 6...
## 7   230519.99 MULTIPOLYGON (((-75.59853 6...
## 8   343515.45 MULTIPOLYGON (((-75.59437 6...
## 9   306313.78 MULTIPOLYGON (((-75.59025 6...
## 10  498922.08 MULTIPOLYGON (((-75.58971 6...

Si se quiere añadir una variable a un mapa en formato “sf”.

En este caso se añade la columna NOMBREBARRIO, para tener el nombre del barrio sin el problema de las tildes.

# En caso de añadir alguna columna de una base de datos a otra en formato sf.
bd_barrios_2 <- st_drop_geometry(bd_barrios_sf)
barrios_env <- barrios_env %>% 
  left_join(bd_barrios_2 %>% select(Cod, NOMBARRIO), 
            by = c("cod" = "Cod"))
barrios_env
## Simple feature collection with 39 features and 10 fields
## geometry type:  POLYGON
## dimension:      XY
## bbox:           xmin: -75.60517 ymin: 6.141683 xmax: -75.55978 ymax: 6.188921
## geographic CRS: WGS84(DD)
## # A tibble: 39 x 11
##    barrio   cod hectareas   km_2 nombarrio objectid shape_area shape_leng zona 
##    <chr>  <dbl>     <dbl>  <dbl> <chr>        <dbl>      <dbl>      <dbl> <chr>
##  1 039       39     16.6  0.166  BOSQUES …        1    166170.      1732. 02   
##  2 038       38     22.7  0.227  VILLAGRA…        2    226544.      2363. 02   
##  3 036       36     18.4  0.184  PONTEVED…        3    183766.      1975. 02   
##  4 037       37     13.2  0.132  JARDINES         4    131625.      1696. 02   
##  5 009        9    134.   1.34   LAS VEGAS        5   1339512.      8151. 01   
##  6 008        8      6.71 0.0671 LAS CASI…        6     67091.      1084. 08   
##  7 010       10     23.1  0.231  LA PRIMA…        7    230520.      1930. 08   
##  8 011       11     34.4  0.344  LA PAZ           8    343515.      2959. 07   
##  9 012       12     30.6  0.306  MILAN VA…        9    306314.      2479. 08   
## 10 013       13     49.9  0.499  EL DORADO       10    498922.      3698. 07   
## # … with 29 more rows, and 2 more variables: geometry <POLYGON [°]>,
## #   NOMBARRIO <chr>

Lectura de la base de datos de las Sedes Administrativas del municipio de envigado.

Se pueden encontrar en:

https://www.datos.gov.co/Funci-n-p-blica/Sedes-Administrativas-Municipio-de-Envigado/7nv5-fy9z

Procedimiento para tomar las coordenadas y convertir la base de datos en un mapa.

sedes_admin_env <- read.csv("Sedes_Administrativas_Municipio_de_Envigado.csv")
sedes_admin_env <- sedes_admin_env %>%
  separate(Coordenadas, into = c(NA, "Y", "X", NA), sep = "[\\(,\\)]") %>%
  mutate(Y = as.numeric(Y),
         X = as.numeric(X))
sedes_admin_env_sf <- st_as_sf(sedes_admin_env, coords = c("X", "Y"))
sedes_admin_env_sf
## Simple feature collection with 49 features and 7 fields
## geometry type:  POINT
## dimension:      XY
## bbox:           xmin: -75.60263 ymin: 6.149386 xmax: -75.53398 ymax: 6.175923
## CRS:            NA
## First 10 features:
##                                                      SEDE
## 1  Agencia Pública De Gestión Y Colocación Para El Empleo
## 2                   Archivo Central Municipio De Envigado
## 3                                                  Carcel
## 4                                        Casa De Justicia
## 5                Casa De La Cultura Miguel Uribe Restrepo
## 6   Centro De Encuentro Ciudadano Y Vida Casa El Escobero
## 7       Centro De Encuentro Ciudadano Y Vida Casa Linares
## 8          Centro De Encuentro Ciudadano Y Vida El Salado
## 9                          Centro Gerontológico Atardeser
## 10                            Comisaría Primera Y Segunda
##                              Direccion Telefono         Ext
## 1                Carrera 43A 38 Sur 60  3394000        4682
## 2               Diagonal 31 34B Sur 36  3331213   No aplica
## 3                Carrera 43A 38 Sur 35  3394000        4034
## 4                 Calle 40 Sur 24F 106  3394000 4713 - 4731
## 5                Carrera 45 34A Sur 65  3394000        4426
## 6                  Calle 36D Sur 27 40  3394000        4773
## 7  Calle 36 Sur 25 132 Loma del Chocho  3361590   No aplica
## 8                  Calle 40 Sur 24E 75  3394000        4830
## 9           Transversal 34E Sur 33A 35  3394000        4355
## 10   Carrera 43A 38 Sur 54 Primer piso  3394000 4035 - 4091
##                                                                                                                                                                                                                     Horario.de.Atencion
## 1                                                                                                                    Lunes a jueves de 7:00 am a 12:00 pm y de 2:00 pm a 6:00 pm. Viernes de 7:00 am a 12:00 pm y de 1:00 pm a 5:00 pm.
## 2                                                                                                           Lunes a jueves de 7:30 a.m. a 12:00 m y de 1:30 p.m.a 4:30 p.m. y Viernes de 7:30 a.m. a 12:00 m y de 1:00 p.m. a 4:00 p.m.
## 3                                                                                                                                                         El servicio se prestara de manera permanente, es decir las 24 horas del dí­a.
## 4                                                                                                                    Lunes a jueves de 7:00 am a 12:00 pm y de 2:00 pm a 6:00 pm. Viernes de 7:00 am a 12:00 pm y de 1:00 pm a 5:00 pm.
## 5                                                                                                                                                                 Lunes a jueves: 7:00 a.m. a 7:00 p.m. y Sábado: 8:00 a.m. a 6:00 p.m.
## 6                                                                                                                    Lunes a jueves de 7:00 am a 12:00 pm y de 2:00 pm a 6:00 pm. Viernes de 7:00 am a 12:00 pm y de 1:00 pm a 5:00 pm.
## 7                                                                                                                    Lunes a jueves de 7:00 am a 12:00 pm y de 2:00 pm a 6:00 pm. Viernes de 7:00 am a 12:00 pm y de 1:00 pm a 5:00 pm.
## 8                                                                                                              Lunes a Jueves de 8:00 a.m. a 1:00 y de 2:00 p.m. a 6:00 p.m. Viernes de 8:00 a.m. a 12:00 m. y de 1:00 p.m. a 5:00 p.m.
## 9                                                                                                                    Lunes a jueves de 7:00 am a 12:00 pm y de 2:00 pm a 6:00 pm. Viernes de 7:00 am a 12:00 pm y de 1:00 pm a 5:00 pm.
## 10 Lunes a jueves de 7.00 a.m. a 12:00 m y de 2:00 p.m. a 6:00 p.m. a Viernes de 7:00 a.m. a 12:00 m y de 1:00 p.m. a 5:00 p.m. NOTA: Cada semana, una de las comisarias de familia estaría de turno en jornada continua de 7:00 a 4:00
##                   Funcionario.Enlace              Correo.electronico
## 1     Claudia Patricia Uribe Huertas   claudia.urive@envigado.gov.co
## 2  Indira Daliana Sánchez Torregrosa  indira.sanchez@envigado.gov.co
## 3             Hernán Arroyave Múnera hernan.arroyave@envigado.gov.co
## 4         Carlos Arturo López García    carlos.lopez@envigado.gov.co
## 5     Clara Elena Vargas Aristizabal    clara.vargas@envigado.gov.co
## 6          Luz Dary Castro Jaramillo      luz.castro@envigado.gov.co
## 7   Claudia Milena Salazar Velásquez claudia.salazar@envigado.gov.co
## 8         Ruby Janet García González     ruby.garcia@envigado.gov.co
## 9         Diana María Andrade Cuervo   diana.andrade@envigado.gov.co
## 10         Zulma Stella Isaza Arango     zulma.isaza@envigado.gov.co
##                      geometry
## 1  POINT (-75.58888 6.169993)
## 2   POINT (-75.57906 6.17246)
## 3  POINT (-75.58834 6.169554)
## 4  POINT (-75.57759 6.151587)
## 5   POINT (-75.59096 6.17307)
## 6  POINT (-75.57073 6.162559)
## 7  POINT (-75.56605 6.167601)
## 8   POINT (-75.5769 6.149386)
## 9  POINT (-75.58331 6.169336)
## 10  POINT (-75.58895 6.17006)
plot(st_geometry(sedes_admin_env_sf))

Desplogue de mapa de puntos con opciones.

st_crs(sedes_admin_env_sf) <- 4326
plot(st_geometry(sedes_admin_env_sf), pch = 19, col = "darkblue", 
     axes = TRUE, las = 1)

Llevar el mapa a coordenadas planas. En esta caso a CRS = 3116, (CRS: Coordinate Reference System) que corresponde al datuem Bogotá en Magnas/SIRGAS (EPSG = 3116, EPSG: European Petroleum Survey Group).

https://spatialreference.org/

st_crs(sedes_admin_env_sf)
## Coordinate Reference System:
##   User input: EPSG:4326 
##   wkt:
## GEOGCRS["WGS 84",
##     DATUM["World Geodetic System 1984",
##         ELLIPSOID["WGS 84",6378137,298.257223563,
##             LENGTHUNIT["metre",1]]],
##     PRIMEM["Greenwich",0,
##         ANGLEUNIT["degree",0.0174532925199433]],
##     CS[ellipsoidal,2],
##         AXIS["geodetic latitude (Lat)",north,
##             ORDER[1],
##             ANGLEUNIT["degree",0.0174532925199433]],
##         AXIS["geodetic longitude (Lon)",east,
##             ORDER[2],
##             ANGLEUNIT["degree",0.0174532925199433]],
##     USAGE[
##         SCOPE["unknown"],
##         AREA["World"],
##         BBOX[-90,-180,90,180]],
##     ID["EPSG",4326]]
sedes_admin_env_sf_planas <- st_transform(sedes_admin_env_sf, crs = 3116)
plot(st_geometry(sedes_admin_env_sf_planas), axes = TRUE, 
     las = 1)

Superposición de mapas.

plot(st_geometry(barrios_env))
plot(st_geometry(sedes_admin_env_sf), pch = 19, col = "darkblue", add = TRUE)

Cargar un mapa de fondo para superponer los mapas tipo vector.

mapa_envig <- get_map(getbb("Envigado"), source = "osm")
## Source : http://tile.stamen.com/terrain/14/4750/7908.png
## Source : http://tile.stamen.com/terrain/14/4751/7908.png
## Source : http://tile.stamen.com/terrain/14/4752/7908.png
## Source : http://tile.stamen.com/terrain/14/4753/7908.png
## Source : http://tile.stamen.com/terrain/14/4750/7909.png
## Source : http://tile.stamen.com/terrain/14/4751/7909.png
## Source : http://tile.stamen.com/terrain/14/4752/7909.png
## Source : http://tile.stamen.com/terrain/14/4753/7909.png
## Source : http://tile.stamen.com/terrain/14/4750/7910.png
## Source : http://tile.stamen.com/terrain/14/4751/7910.png
## Source : http://tile.stamen.com/terrain/14/4752/7910.png
## Source : http://tile.stamen.com/terrain/14/4753/7910.png
## Source : http://tile.stamen.com/terrain/14/4750/7911.png
## Source : http://tile.stamen.com/terrain/14/4751/7911.png
## Source : http://tile.stamen.com/terrain/14/4752/7911.png
## Source : http://tile.stamen.com/terrain/14/4753/7911.png
## Source : http://tile.stamen.com/terrain/14/4750/7912.png
## Source : http://tile.stamen.com/terrain/14/4751/7912.png
## Source : http://tile.stamen.com/terrain/14/4752/7912.png
## Source : http://tile.stamen.com/terrain/14/4753/7912.png
plot(mapa_envig)

st_crs(bd_barrios_sf) <- 4326
ggmap(mapa_envig) +
  geom_sf(data = bd_barrios_sf,
          inherit.aes = FALSE, 
          fill = "transparent") +
  geom_sf(data = sedes_admin_env_sf,
          inherit.aes = FALSE)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.

load("accidentalidad_Envigado.RData")

Cálculo del número de accidentes.

accidentes_env <- acc_env %>% 
  group_by(RADICADO, BARRIO) %>% 
  summarise(num_accidentados = n())
## `summarise()` regrouping output by 'RADICADO' (override with `.groups` argument)
accidentes_env_x_barrio <- accidentes_env %>% 
  group_by(BARRIO) %>% 
  summarise(num_accidentes = n(),
            log_num_accidentes = log10(num_accidentes)) %>% 
  mutate(barrio = tolower(BARRIO)) %>% 
  arrange(desc(num_accidentes))
## `summarise()` ungrouping output (override with `.groups` argument)
accidentes_env_x_barrio$barrio <- factor(accidentes_env_x_barrio$barrio,
                                         levels = accidentes_env_x_barrio$barrio)
ggplot(accidentes_env_x_barrio, aes(barrio, num_accidentes)) +
  geom_bar(stat = "identity") +
  coord_flip()

ggplot(accidentes_env_x_barrio, aes(barrio, log_num_accidentes)) +
  geom_bar(stat = "identity") +
  coord_flip()

bd_barrios_sf <- bd_barrios_sf %>% 
  mutate(nombarrio = tolower(NOMBARRIO))

Subir la información del número de accidentes por barrio.

bd_barrios_sf_acc <- bd_barrios_sf %>% 
  inner_join(accidentes_env_x_barrio, by = c("nombarrio" = "barrio"))
plot(bd_barrios_sf_acc["log_num_accidentes"])

ggmap(mapa_envig) +
  geom_sf(data = bd_barrios_sf_acc,
          inherit.aes = FALSE, 
          aes(fill = log_num_accidentes),
          alpha = 0.6) +
  geom_sf(data = sedes_admin_env_sf,
          inherit.aes = FALSE) +
   scale_fill_gradient(low = "yellow", high = "red", na.value = NA)
## Coordinate system already present. Adding new coordinate system, which will replace the existing one.